package database.dao.Impl;

import database.dao.InvoiceDao;
import entity.Commodity;
import entity.Invoice;
import entity.InvoiceRecord;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName InvoiceDaoImpl
 * @Description TODO
 * @Author lzq
 * @Date 2021/6/17 8:52
 */
public class InvoiceDaoImpl extends BaseDao implements InvoiceDao {
    @Override
    public String addInvoice(Invoice invoice) {
        String psql="insert into Invoice(customer_id,total_price)" +
                "values(?,?)";
        Object[] values={invoice.getCustomer_id(),invoice.getTotal_price()};
        super.executeUpdate(psql,values);
        return ((Integer)super.getAutoId("Invoice","invoice_id")).toString();
    }

    @Override
    public List<InvoiceRecord> SelectInvoice(String customer_id) {
        ResultSet resultSet = null;
        String psql="SELECT i.`invoice_id`,i.`total_price`,i.`invoice_date`\n" +
                "FROM invoice i\n" +
                "WHERE i.`customer_id`=?";
        Object[] value= new Object[]{customer_id};
        resultSet= super.executeQuerySQL(psql,value);

        List<InvoiceRecord>invoiceRecords=new ArrayList<>();
        if(resultSet!=null){
            try{
                while(resultSet.next()){
                    Integer invoice_id=resultSet.getInt("invoice_id");
                    Float total_price=resultSet.getFloat("total_price");
                    Timestamp timestamp=resultSet.getTimestamp("invoice_date");
                    Date date=new Date(timestamp.getTime());

                    invoiceRecords.add(new InvoiceRecord(invoice_id,total_price.toString(),date.toString()));
                }
            }catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return invoiceRecords;
    }
}
